<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function competitors_add_page($id) {
    return drupal_get_form('competitors_edit_form',$id);
}

function competitors_edit_page($id) {
    return drupal_get_form('competitors_edit_form', $id);
}

function competitors_clone_page($id) {
    return drupal_get_form('competitors_edit_form', $id);
}

function competitors_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('competitors', 'competitors_id', $id);
        if (empty($record)) {
            drupal_set_message(t('竞争品牌价格信息不存在！'), 'status', FALSE);
            return $form;
        }
        $form_state['update'] = true;
        $form_state['id'] = $id;
    }else{
        $form_state['insert'] = true;
    }
    // 判断用户角色
    if(!nonghua_user_access('competitors', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    if (empty($record)) {
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 1, FALSE, null,'省必填');
        _insert_fertilizer_selection_form($form,null);
        _insert_brand_selection_form($form,null);
        _insert_date_selection_form($form,$form_state,5,date("Y"),date("m"),true);

    } else {
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 1, FALSE, $record->addr_id,'省必填');
        _insert_fertilizer_selection_form($form,$record->fertilizer_id);
        _insert_brand_selection_form($form,$record->brand_id);
        $dateArr = explode('-',$record->date);
        _insert_date_selection_form($form,$form_state,5,$dateArr[0],$dateArr[1],true);
    }

    $form['n'] = array(
        '#type' => 'textfield',
        '#title' => 'N',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->n:'',
        '#attributes'=>array('id'=>'n'),
    );
    $form['p'] = array(
        '#type' => 'textfield',
        '#title' => 'P',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->p:'',
        '#attributes'=>array('id'=>'p'),
    );
    $form['k'] = array(
        '#type' => 'textfield',
        '#title' => 'K',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->k:'',
        '#attributes'=>array('id'=>'k'),
    );
    $form['npk_total'] = array(
        '#type' => 'textfield',
        '#title' => '总含量',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->npk_total:'',
        '#disabled'=>TRUE,
        '#attributes'=>array('id'=>'npk_total'),
    );
    $form['sm'] = array(
        '#type' => 'select',
        '#title' => 'S/M',
        '#required' => TRUE,
        '#options'=>array('MOP'=>'MOP','SOP'=>'SOP'),
        '#default_value' => !empty($record) ? $record->sm:'',
    );
    $form['factory_price'] = array(
        '#type' => 'textfield',
        '#title' => '出厂价格',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->factory_price:'',
    );
    $form['arrival_price'] = array(
        '#type' => 'textfield',
        '#title' => '到站价格',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->arrival_price:'',
    );
    $form['retail_price'] = array(
        '#type' => 'textfield',
        '#title' => '零售价格',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->retail_price:'',
    );
    $form['rebate'] = array(
        '#type' => 'textfield',
        '#title' => '返利',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#default_value' => !empty($record) ? $record->rebate:0,
    );
    $form['sales_policy'] = array(
        '#type' => 'textarea',
        '#title' => '销售政策',
        '#cols' => 32,
        '#rows' => 2,
        '#maxlength' => 200,
        '#default_value' => !empty($record) ? $record->sales_policy:'',
    );
    if(arg(1) === 'add'){
        $submit = '添加';
    }else if(arg(1) == 'edit'){
        $submit = '修改';
    }else if(arg(1) == 'clone'){
        $submit = '克隆';
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $submit,
        '#access' => nonghua_user_access('competitors', 'edit', $id, !empty($record) ? $record->author_uid:0, 0)
    );
    return $form;
}

function competitors_edit_form_validate($form, &$form_state) {
    $empty = false;
    if(empty($form_state['values']['province'])){
        form_set_error('province', '必须填写 地址');
        $empty = true;
    }
    if(empty($form_state['values']['year'])){
        form_set_error('year', '必须填写 年份');
        $empty = true;
    }
    if(empty($form_state['values']['month'])){
        form_set_error('month', '必须填写 月份');
        $empty = true;
    }
    if(empty($form_state['values']['fertilizer'])){
        form_set_error('fertilizer', '必须填写 肥料类别');
        $empty = true;
    }
    if(empty($form_state['values']['brand'])){
        form_set_error('brand', '必须填写 化肥品牌');
        $empty = true;
    }
    if(!empty($form_state['values']['n'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['n']) || (strlen(explode('.',$form_state['values']['n'])[0])>8)) {
            form_set_error('n', "N格式错误");
        }
    }
    if(!empty($form_state['values']['p'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['p']) || (strlen(explode('.',$form_state['values']['p'])[0])>8)) {
            form_set_error('p', "P格式错误");
        }
    }
    if(!empty($form_state['values']['k'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['k']) || (strlen(explode('.',$form_state['values']['k'])[0])>8)) {
            form_set_error('k', "K格式错误");
        }
    }
    if(!empty($form_state['values']['npk_total'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['npk_total']) || (strlen(explode('.',$form_state['values']['npk_total'])[0])>8)) {
            form_set_error('npk_total', "总容量格式错误");
        }
    }
    if(!empty($form_state['values']['factory_price'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['factory_price']) || (strlen(explode('.',$form_state['values']['factory_price'])[0])>8)) {
            form_set_error('factory_price', "出厂价格格式错误");
        }
    }
    if(!empty($form_state['values']['arrival_price'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['arrival_price']) || (strlen(explode('.',$form_state['values']['arrival_price'])[0])>8)) {
            form_set_error('arrival_price', "到站价格格式错误");
        }
    }
    if(!empty($form_state['values']['retail_price'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['retail_price']) || (strlen(explode('.',$form_state['values']['retail_price'])[0])>8)) {
            form_set_error('retail_price', "零售价格格式错误");
        }
    }
    if(!empty($form_state['values']['rebate'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['rebate']) || (strlen(explode('.',$form_state['values']['rebate'])[0])>8)) {
            form_set_error('rebate', "返利格式错误");
        }
    }
    if(!empty($form_state['values']['sales_policy'])){
        if(strlen($form_state['values']['sales_policy']) > 200){
            form_set_error('sales_policy', '销售政策 不能超过 200 个字符，但现在已经 '.strlen($form_state['values']['sales_policy']).' 个字符了');
            $empty = true;
        }
    }

    if(arg(1)=='clone' || (!$empty && isset($form_state['insert']) && $form_state['insert'])){
        $address = _get_address_id($form_state);
        $query = db_select('competitors', 's');
        $query->condition('s.addr_id',$address);
        $query->condition('s.date', $form_state['values']['year'].'-'.$form_state['values']['month'].'-'.'01');
        $query->condition('s.fertilizer_id',$form_state['values']['fertilizer']);
        $query->condition('s.brand_id',$form_state['values']['brand']);
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if(!empty($record)){
            form_set_error('',"该地区在".$form_state['values']['year']."年".$form_state['values']['month']."月"."该肥料类别下的"."该化肥品牌信息已存在" );
        }
    }
    if(arg(1)=='clone' ||(!$empty && isset($form_state['update']) && $form_state['update'])) {
        $address = _get_address_id($form_state);
        $query = db_select('competitors', 's');
        $query->condition('s.addr_id',$address);
        $query->condition('s.date', $form_state['values']['year'].'-'.$form_state['values']['month'].'-'.'01');
        $query->condition('s.fertilizer_id',$form_state['values']['fertilizer']);
        $query->condition('s.brand_id',$form_state['values']['brand']);
        $query->condition('s.competitors_id', $form_state['id'], '!=');
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if(!empty($record)){
            form_set_error('',"该地区在".$form_state['values']['year']."年".$form_state['values']['month']."月"."该肥料类别下的"."该化肥品牌信息已存在" );
        }
    }

}

function competitors_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address = _get_address_id($form_state);
    if (arg(1) == 'add') { //add new competitors
        $nid = db_insert('competitors') // Table name no longer needs {}
        ->fields(array(
            'addr_id' => $address,
            'fertilizer_id' => $form_state['values']['fertilizer'],
            'brand_id' => $form_state['values']['brand'],
            'date' => $form_state['values']['year'].'-'.$form_state['values']['month'].'-'.'01',
            'n' => $form_state['values']['n'],
            'p' => $form_state['values']['p'],
            'k' => $form_state['values']['k'],
            'npk_total' => $form_state['values']['n']+$form_state['values']['p']+$form_state['values']['k'],
            'sm' => $form_state['values']['sm'],
            'factory_price' => $form_state['values']['factory_price'],
            'arrival_price' => $form_state['values']['arrival_price'],
            'retail_price' => $form_state['values']['retail_price'],
            'rebate' => $form_state['values']['rebate'],
            'sales_policy' => $form_state['values']['sales_policy'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            drupal_goto('competitors/add/'.$nid);
        }
//        drupal_goto('competitors/list');
    } else {
        if(arg(1) == 'clone'){
            $nid = db_insert('competitors') // Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'fertilizer_id' => $form_state['values']['fertilizer'],
                'brand_id' => $form_state['values']['brand'],
                'date' => $form_state['values']['year'].'-'.$form_state['values']['month'].'-'.'01',
                'n' => $form_state['values']['n'],
                'p' => $form_state['values']['p'],
                'k' => $form_state['values']['k'],
                'npk_total' => $form_state['values']['npk_total'],
                'sm' => $form_state['values']['sm'],
                'factory_price' => $form_state['values']['factory_price'],
                'arrival_price' => $form_state['values']['arrival_price'],
                'retail_price' => $form_state['values']['retail_price'],
                'rebate' => $form_state['values']['rebate'],
                'sales_policy' => $form_state['values']['sales_policy'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('克隆成功！'), 'status', FALSE);
                drupal_goto('competitors/list');
            }
        }else{
            $nid = db_update('competitors') // edit exsting store. todo: update only modified fields
            ->fields(array(
                'addr_id' => $address,
                'fertilizer_id' => $form_state['values']['fertilizer'],
                'brand_id' => $form_state['values']['brand'],
                'date' => $form_state['values']['year'].'-'.$form_state['values']['month'].'-'.'01',
                'n' => $form_state['values']['n'],
                'p' => $form_state['values']['p'],
                'k' => $form_state['values']['k'],
                'npk_total' => $form_state['values']['npk_total'],
                'sm' => $form_state['values']['sm'],
                'factory_price' => $form_state['values']['factory_price'],
                'arrival_price' => $form_state['values']['arrival_price'],
                'retail_price' => $form_state['values']['retail_price'],
                'rebate' => $form_state['values']['rebate'],
                'sales_policy' => $form_state['values']['sales_policy'],
    //            'author_uid' => $user->uid,
                'timestamp' => time(),))
                -> condition('competitors_id',$id, '=')
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('修改成功！'), 'status', FALSE);
            }
        }

//        drupal_goto('competitors/list');
    }
}

